const exec = require('child_process').exec
//cmdPath:winrar.exe路径
//zipPath:压缩包文件
//outPath:解压文件目录
//加密密码
function unzipCmd (cmdPath,zipPath,outPath,pwd) {
    // 任何你期望执行的cmd命令，ls都可以
    
    let cmdStr1 = 'WinRAR.exe -ibck -y x -t -p'+pwd+' "'+zipPath+'"  "'+outPath+'"'
   // cmdStr1 = '"'+cmdPath+'"'+' -ibck -y x -t -p'+pwd+' "'+zipPath+'"  "'+outPath+'"'
    //let cmdPath = cmdPath
    // 子进程名称
    console.log(cmdStr1);
    let workerProcess
    return runExec(cmdStr1)
    function runExec (cmdStr) {
        return new Promise((_resolve, _reject) => { 
            var _result = 1;
            workerProcess = exec(cmdStr, { cwd: cmdPath })
            // 打印正常的后台可执行程序输出
            workerProcess.stdout.on('data', function (data) {
                console.log('stdout: ' + data)
                
            })
            // 打印错误的后台可执行程序输出
            workerProcess.stderr.on('data', function (data) {
                console.log('stderr: ' + data)
                _result = 0;
                _reject();
            })
            // 退出之后的输出
            workerProcess.on('close', function (code) {
                console.log('out code：' + code)
                _resolve(_result)
                if(code==0)
                {
                    console.log('password：' + pwd)
                }
                else
                {
                    unzipCmd(cmdPath,zipPath,outPath,generatePassword(6))
                }
            })
        });
    }
}


const crypto = require('crypto');

const passwordList = [];

function generatePassword(length) {
  const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  //const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=~`[]{}|:;"<>,.?/';
  let password = '';

  do {
    password = '';
    for (let i = 0; i < length; i++) {
      const randomIndex = crypto.randomInt(0, characters.length);
      password += characters[randomIndex];
    }
  } while (passwordList.includes(password));

  passwordList.push(password);
  return password;
}

// 生成一个长度为 8 的密码
const password1 = generatePassword(8);
console.log(password1);

// 再次调用生成密码函数，将返回一个新的不重复密码
const password2 = generatePassword(8);
console.log(password2);
 

//node .\temp\unzip.js "C:\Program Files\WinRAR" "D:\Temp\test.rar" "D:\Temp\" 123456

// 通过命令行参数调用函数
if (process.argv.length >= 5) {
    console.log(process.argv)
   // var temp=  unzipCmd(process.argv[2],process.argv[3],process.argv[4],process.argv[5])
   var temp=  unzipCmd(process.argv[2],process.argv[3],process.argv[4],generatePassword(6))
    console.log(temp)
}